package main

import (
	"fmt"
	"github.com/pebbe/zmq4"
	"log"
	"time"
	// "time"
)

func main() {
	log.SetFlags(log.Lshortfile)
	ce := func(err error) {
		if err != nil {
			log.Panic(err)
		}
	}
	senderSrv := func() {
		context, err := zmq4.NewContext()
		ce(err)
		sender, err := context.NewSocket(zmq4.PUSH)
		ce(err)
		err = sender.Bind("tcp://0.0.0.0:5557")
		ce(err)

		sink, err := context.NewSocket(zmq4.PUSH)
		ce(err)
		err = sink.Connect("tcp://0.0.0.0:5558")
		ce(err)
		_, err = sink.SendMessage("0")
		ce(err)
		cnt := 0
		for i := 10; i < 20; i++ {
			_, err = sender.SendMessage(fmt.Sprintf("%d", i))
			ce(err)
			cnt += i
		}
		log.Println("excepted cost %d", cnt)
	}
	workSrv := func() {
		context, err := zmq4.NewContext()
		ce(err)
		receiver, err := context.NewSocket(zmq4.PULL)
		ce(err)
		err = receiver.Connect("tcp://0.0.0.0:5557")
		ce(err)
		sender, err := context.NewSocket(zmq4.PUSH)
		ce(err)
		err = sender.Connect("tcp://0.0.0.0:5558")
		ce(err)
		for {
			res, err := receiver.RecvMessage(zmq4.SNDMORE)
			ce(err)
			log.Println(res)
			var n int64
			fmt.Sscanf(res[0], "%d", &n)
			time.Sleep(time.Millisecond * 100 * time.Duration(n))
			_, err = sender.SendMessage(res)
			ce(err)
		}
	}
	taskSinkSrv := func() {
		context, err := zmq4.NewContext()
		ce(err)
		receiver, err := context.NewSocket(zmq4.PULL)
		ce(err)
		err = receiver.Bind("tcp://0.0.0.0:5558")
		ce(err)
		now := time.Now()
		for i := 0; i < 10; i++ {
			res, err := receiver.RecvMessage(zmq4.SNDMORE)
			ce(err)
			log.Println(res)
		}
		log.Println("real:", time.Now().Sub(now))
	}
	go func() {
		senderSrv()
	}()
	// go workSrv()
	// go workSrv()
	// go workSrv()
	// go workSrv()
	// go workSrv()
	// go workSrv()
	go workSrv()
	taskSinkSrv()
}
